package com.yanxx.codegenerator.storage.impl;

import com.yanxx.codegenerator.storage.CodeGeneratorState;
import com.yanxx.codegenerator.storage.CodeGeneratorStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;

/**
 * 内存存储实现
 * 仅在内存中保存编号数据，应用重启后数据会丢失
 */
public class MemoryStorage implements CodeGeneratorStorage {
    private static final Logger logger = LoggerFactory.getLogger(MemoryStorage.class);
    
    private long currentMaxValue;
    private final Set<String> confirmedCodes;
    private final Set<String> pendingCodes;
    private final Set<String> recycledCodes;
    
    /**
     * 构造函数
     */
    public MemoryStorage() {
        this.currentMaxValue = 0;
        this.confirmedCodes = new HashSet<>();
        this.pendingCodes = new HashSet<>();
        this.recycledCodes = new HashSet<>();
        logger.info("Initialized memory storage");
    }
    
    @Override
    public boolean save(long currentMaxValue, Set<String> confirmedCodes, Set<String> pendingCodes, Set<String> recycledCodes) {
        this.currentMaxValue = currentMaxValue;
        
        this.confirmedCodes.clear();
        if (confirmedCodes != null) {
            this.confirmedCodes.addAll(confirmedCodes);
        }
        
        this.pendingCodes.clear();
        if (pendingCodes != null) {
            this.pendingCodes.addAll(pendingCodes);
        }
        
        this.recycledCodes.clear();
        if (recycledCodes != null) {
            this.recycledCodes.addAll(recycledCodes);
        }
        
        logger.debug("Saved state to memory, currentMaxValue: {}, confirmedCodes: {}, pendingCodes: {}, recycledCodes: {}",
                currentMaxValue, confirmedCodes != null ? confirmedCodes.size() : 0, 
                pendingCodes != null ? pendingCodes.size() : 0, 
                recycledCodes != null ? recycledCodes.size() : 0);
        
        return true;
    }
    
    @Override
    public CodeGeneratorState load() {
        CodeGeneratorState state = new CodeGeneratorState();
        state.setCurrentMaxValue(currentMaxValue);
        state.setConfirmedCodes(new HashSet<>(confirmedCodes));
        state.setPendingCodes(new HashSet<>(pendingCodes));
        state.setRecycledCodes(new HashSet<>(recycledCodes));
        
        logger.debug("Loaded state from memory, currentMaxValue: {}, confirmedCodes: {}, pendingCodes: {}, recycledCodes: {}",
                currentMaxValue, confirmedCodes.size(), pendingCodes.size(), recycledCodes.size());
        
        return state;
    }
    
    @Override
    public boolean clear() {
        currentMaxValue = 0;
        confirmedCodes.clear();
        pendingCodes.clear();
        recycledCodes.clear();
        
        logger.info("Cleared memory storage");
        
        return true;
    }
}